package org.qhhc.bionioaio.aio.server;

import java.io.Closeable;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ChatServer {
    private static final String LOCALHOST = "127.0.0.1";
    private static final int DEFAULT_PORT = 8888;
    private static final String QUIT = "quit";
    private static final int BUFFER = 1024;

    private AsynchronousServerSocketChannel serverChannel;
    private AsynchronousChannelGroup asynchronousChannelGroup;
    private List<ClientHandler> connectedClients;
    private Charset charset = StandardCharsets.UTF_8;
    private int port;
    public ChatServer(int port) {
        this.port = port;
        connectedClients = new ArrayList<>();
    }
    public ChatServer(){
        this(DEFAULT_PORT);
    }
    public void start(){
        try {
            ExecutorService executor = Executors.newFixedThreadPool(10);
             asynchronousChannelGroup = AsynchronousChannelGroup.withThreadPool(executor);
             serverChannel = AsynchronousServerSocketChannel.open(asynchronousChannelGroup);
             serverChannel.bind(new InetSocketAddress(LOCALHOST, port));
            System.out.println("Server started on port " + port);
            while (true) {
                // 异步连接接收
                
                serverChannel.accept(null,new AcceptHandler());
                System.in.read();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            close(serverChannel);
        }
    }
    private class AcceptHandler implements CompletionHandler<AsynchronousSocketChannel, Object> {
        @Override
        public void completed(AsynchronousSocketChannel clientChannel, Object attachment) {
            if (serverChannel.isOpen()){
                serverChannel.accept(null, this);
            }
            if (clientChannel != null && clientChannel.isOpen()){
                // 微信链接创建一个handler 用于读写操作
                ClientHandler clientHandler = new ClientHandler(clientChannel);
                ByteBuffer buffer = ByteBuffer.allocate(BUFFER);
                addClient(clientHandler);
                clientChannel.read(buffer, buffer, clientHandler);

            }
        }

        @Override
        public void failed(Throwable exc, Object attachment) {
            System.out.println("连接失败"+exc.getMessage());
        }
    }
    private class ClientHandler implements CompletionHandler<Integer, ByteBuffer> {
        private AsynchronousSocketChannel clientChannel;
        private ClientHandler(AsynchronousSocketChannel clientChannel){
            this.clientChannel = clientChannel;
        }
        private AsynchronousSocketChannel getClientChannel(){
            return clientChannel;
        }

        @Override
        public void completed(Integer result, ByteBuffer buffer) {
           if (buffer!=null){
               if(result <= 0){
                   removeClient(this);
               }else {
                   buffer.flip();
                   String fwdMsg = receive(buffer);
                   System.out.println(getClientName(clientChannel)+fwdMsg);
                   forwardMsg(clientChannel,fwdMsg);
                   buffer.clear();
                   if (readToQuit(fwdMsg)){
                       removeClient(this);
                   }else {
                       clientChannel.read(buffer,buffer,this);
                   }
               }
           }
        }

        @Override
        public void failed(Throwable exc, ByteBuffer attachment) {
            System.out.println("读写操作失败"+exc.getMessage());
        }
    }

    private void forwardMsg(AsynchronousSocketChannel clientChannel, String fwdMsg) {
        for (ClientHandler connectedHandler : connectedClients) {
            AsynchronousSocketChannel client = connectedHandler.getClientChannel();
            if (!client.equals(clientChannel)){
                try {
                    ByteBuffer buffer = charset.encode(getClientName(client)+fwdMsg);
                    client.write(buffer,null,connectedHandler);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    private String receive(ByteBuffer buffer) {
        return String.valueOf(charset.decode(buffer));
    }

    private boolean readToQuit(String fwdMsg) {
        return fwdMsg.equals(QUIT);
    }


    private synchronized void addClient(ClientHandler clientHandler){
        connectedClients.add(clientHandler);
        System.out.println(getClientName(clientHandler.getClientChannel())+"已经连接");
    }
    private void removeClient(ClientHandler clientHandler) {
        AsynchronousSocketChannel clientChannel = clientHandler.getClientChannel();
        connectedClients.remove(clientHandler);
        System.out.println(getClientName(clientChannel)+"已经断开连接");
        close(clientChannel);
    }

    private void close(Closeable closeable) {
        try{
            closeable.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    private String getClientName(AsynchronousSocketChannel clientChannel) {
        int port = -1;
        try {
            InetSocketAddress remoteAddress = (InetSocketAddress) clientChannel.getRemoteAddress();
            port = remoteAddress.getPort();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "客户端["+port+"]:";
    }

    public static void main(String[] args) {
        ChatServer server = new ChatServer();
        server.start();
    }

}
